package com.cloudcc.migrationToNewSys;

import com.alibaba.fastjson.JSONObject;
import com.cloudcc.ccTool.CCObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class MigrationCCService {
    ResourceBundle prb = PropertyResourceBundle.getBundle("application");// 获取配置文件;
    private String username = prb.getString("newcco.username");
    private String safetyMark =prb.getString("newcco.safetyMark");
    private String clientId = prb.getString("newcco.clientId");
    private String secretKey = prb.getString("newcco.secretKey");
    private String grant_type = "password";
    private String orgId = prb.getString("newcco.orgId");
    public String path;//标准接口地址
    public String gatewayUrl = prb.getString("newcco.gatewayUrl");
    public String gatewayUrl() {
        return gatewayUrl;
    }
    public String getToken() {
        String accessToken = "";
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("username", username);
        parObj.put("safetyMark", safetyMark);
        parObj.put("clientId", clientId);
        parObj.put("secretKey", secretKey);
        parObj.put("orgId", orgId);
        parObj.put("grant_type", grant_type);

        path = getOrgApiUrl() + "/api/cauth/token";
        if (!"".equals(path)) {
            String relStr = sendPost(path, parObj.toString());
            JSONObject relObj = new JSONObject();
            relObj = JSONObject.parseObject(relStr);
            boolean result = relObj.getBoolean("result");
            if (result) {
                JSONObject data = (JSONObject) relObj.get("data");
                if (data != null && data.containsKey("accessToken")) {
                    accessToken = relObj.getJSONObject("data").getString("accessToken");
                }
            } else {
                String returnInfo = relObj.getString("returnInfo");

            }
        }
        return accessToken;
    }

    public List<CCObject> cqlQuery(String apiName, String expression) {
        List<CCObject> orst = new ArrayList<CCObject>();
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("serviceName", "cqlQuery"); //服务名
        parObj.put("objectApiName", apiName); //对象名
        parObj.put("expressions", expression); //查询条件
        //拼接接口地址
        path = getOrgApiUrl() + "/openApi/common";
        String relStr = CCPost(path, parObj.toString());
        JSONObject relObj = new JSONObject();
        relObj = JSONObject.parseObject(relStr);
        String result = relObj.getString("result");
        String data = relObj.getString("data");
        if ("true".equals(result) && data != null) {
            List<Map> rst = relObj.getJSONArray("data").toJavaList(Map.class);
            for (Map<String, Object> m : rst) {
                CCObject co = new CCObject(apiName);
                for (Object _key : m.keySet()) {
                    String key = (String) _key;
                    co.put(key, m.get(key));
                }
                orst.add(co);
            }
        }

        return orst;
    }

    public String CCPost(String path, String param) {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String exception = "";
        String result = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = null;
            // 打开和URL之间的连接
            conn = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");    // POST方法
            conn.setConnectTimeout(15 * 1000);// 设置连接超时时间为5秒
            conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
            String tokens = "";
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("accessToken", getToken());
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            // 发送请求参数
            BufferedWriter bw = new BufferedWriter(out);
            bw.write(param);
            // flush输出流的缓冲
            bw.flush();
            // 定义BufferedReader输入流来读取URL的响应
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            exception = "发送 POST 请求出现异常！" + e;
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (sb.toString().isEmpty()) {
            result = exception;
        } else {
            result = sb.toString();
        }
        return result;
    }

    public String getOrgApiUrl() {
        String apiUrl = "";
        String url = prb.getString("newcco.url");;//私有云填写
        if ("".equals(url)) {
            String parUrl = "https://developer.apis.cloudcc.cn/oauth/apidomain?scope=cloudccCRM&orgId=" + orgId;
            String relStr = sendGet(parUrl);
            JSONObject relObj = new JSONObject();
            relObj = JSONObject.parseObject(relStr);
            String result = relObj.getString("result");
            if ("true".equals(result)) {
                apiUrl = relObj.getString("orgapi_address");
            }
        } else {
            apiUrl = url;
        }

        return apiUrl;
    }
    public String sendPost(String path, String param) {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String exception = "";
        String result = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = null;
            // 打开和URL之间的连接
            conn = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");    // POST方法
            conn.setConnectTimeout(15 * 1000);// 设置连接超时时间为5秒
            conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
            String tokens = "";
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            // 发送请求参数
            BufferedWriter bw = new BufferedWriter(out);
            bw.write(param);
            // flush输出流的缓冲
            bw.flush();
            // 定义BufferedReader输入流来读取URL的响应
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            exception = "发送 POST 请求出现异常！" + e;
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (sb.toString().isEmpty()) {
            result = exception;
        } else {
            result = sb.toString();
        }
        return result;
    }

    /**
     * @return java.lang.String
     * @Description //TODO GET请求方法
     * @Author T.han
     * @Date 2023/8/18 10:06
     * @Param path 地址   http://127.0.0.1/cloudcc/outoken?key1=value1&key2=value2
     **/
    public static String sendGet(String path) {
        StringBuffer sb = new StringBuffer();
        String exception = "";
        String result = "";
        try {
            URL url = new URL(path);
            InputStream is = url.openStream();
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String line;//读取数据
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            isr.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            exception = "发送 GET 请求出现异常！" + e;
        }
        if (sb.toString().isEmpty()) {
            result = exception;
        } else {
            result = sb.toString();
        }
        return result;
    }




}
